package com.windbell.rest.security

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.springframework.stereotype.Component
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import com.uniquesoft.uidl.validation.Validates

@Component
class AuthorizationInterceptor extends HandlerInterceptorAdapter { 
    
    override preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        val handlerMethod = (handler as HandlerMethod)
        val method = handlerMethod.method
        val userId = request.getSession(false)?.getAttribute("__userid__")
        if (userId == null && method.getAnnotation(Authorization) != null){
            //EC03 /连接断开，请重新登录
            //this throws an exception , caught in ValidationExceptionHandler
            Validates.reportSingleError("EC03", "连接断开，请重新登录")
            return false
        }else{
            request.setAttribute("__current_user_id__", userId)
            return true
        }
    }
    
}
